<?php
class OrdersAction extends CommonAction {
    private $Orders;

	public function __construct(){
		parent::__construct();
		$this->checkAuth();
	    $this->Orders = D('Orders');
	}
	//空操作
	Public function _empty(){
	    header("HTTP/1.0 404 Not Found");//使HTTP返回404状态码
	    $this->display("Public:404");
	}
    public function index(){
		$per_num = 10;
        $page = chkNum($_POST['page']) ? $_POST['page'] : 1;
		$count = $this->Orders->where('uid='.$this->auth['id'])->count();
        $page_num = ceil($count/$per_num);
		if($page > $page_num) $page = $page_num;
        $list=$this->Orders->where('uid='.$this->auth['id'])->limit(($page-1)*$per_num.','.$per_num)->select();

		foreach($list as $k => $v){
			$list[$k]['total'] = coin($v['price']*$v['num']);
		}

        $this->assign('list',$list);
		$this->assign('page',$page);
		$this->assign('page_num',$page_num);
		$this->assign('empty','<tr><td colspan="8" style="text-align:center">没有找到数据！</td></tr>');
		$this->display('./Tpl/Home/Orders.html');
    }

	public function buy(){
		if($this->sys['ks']==0) exit;

		$num = floatval($_POST['num']);
		$price = floatval($_POST['price']);
		$coin = $_POST['coin'];
		$paypwd = md5(trim($_POST['paypwd']));

        if(!chkNum($num)||!chkNum($price)||!chkStr($coin)||$paypwd!=$this->auth['paypwd']){$this->ajaxReturn('','交易密码不正确！',1);exit;}

		$mo = new Model();
		$mo->query('set autocommit=0');
		$mo->query('lock tables t_user write,t_orders write,t_trans write');
		$total = $num*$price;

        $auth = $mo->table('t_user')->where('id='.$this->auth['id'])->find();
		if($auth['rmb'] < $total){$mo->query('rollback');$this->ajaxReturn('','余额不足！',1);exit;}
		
		$rs[]=$mo->table('t_user')->save(array(
			'id'=>$auth['id'],
			'rmb'=>array('exp','rmb-'.$total),
			'rmb_frozen'=>array('exp','rmb_frozen+'.$total)
		));
		$rs[]=$mo->table('t_orders')->add(array(
			'uid'=>$auth['id'],
			'price'=>$price,
			'num'=>$num,
			'type'=>1,
			'coin'=>$coin,
			'ctime'=>time()
		));

		if(!chkArr($rs)){$mo->query('rollback');$this->ajaxReturn('','提交失败！',1);exit;}

		$mo->query('commit');
		$mo->query('unlock tables');

		$this->runTrade($coin,$price);
		$this->ajaxReturn(1,'提交成功！',0);
	}

	public function sell(){
		if($this->sys['ks']==0) exit;

		$num = floatval($_POST['num']);
		$price = floatval($_POST['price']);
		$coin = $_POST['coin'];
		$paypwd =md5( trim($_POST['paypwd']));

        if(!chkNum($num)||!chkNum($price)||!chkStr($coin)||$paypwd!=$this->auth['paypwd']){$this->ajaxReturn('','交易密码不正确！',1);exit;}

		$mo = new Model();
		$mo->query('set autocommit=0');
		$mo->query('lock tables t_user write,t_orders write,t_trans write');
		$total = $num*$price;

        $auth = $mo->table('t_user')->where('id='.$this->auth['id'])->find();
		if($auth['xnb'] < $num){$mo->query('rollback');$this->ajaxReturn('','余额不足！',1);exit;}
		
		$rs[]=$mo->table('t_user')->save(array(
			'id'=>$auth['id'],
			'xnb'=>array('exp','xnb-'.$num),
			'xnb_frozen'=>array('exp','xnb_frozen+'.$num)
		));
		$rs[]=$mo->table('t_orders')->add(array(
			'uid'=>$auth['id'],
			'price'=>$price,
			'num'=>$num,
			'type'=>0,
			'coin'=>$coin,
			'ctime'=>time()
		));
    
		if(!chkArr($rs)){$mo->query('rollback');$this->ajaxReturn('','提交失败！',1);exit;}

		$mo->query('commit');
		$mo->query('unlock tables');

		$this->runTrade($coin,$price);
        $this->ajaxReturn(0,'提交成功！',0);
	}

	public function runTrade($coin,$price){
	    $mo = new Model();
		$mo->query('set autocommit=0');
		$mo->query('lock tables t_user write,t_orders write,t_trans write');

		for(;;){
			$rs=array();
			$buy=$mo->table('t_orders')->where('status=0 and type=1 and coin="'.$coin.'"')->order('price desc')->find();
			$sell=$mo->table('t_orders')->where('status=0 and type=0 and coin="'.$coin.'"')->order('price asc')->find();
			
			$price_buy=min($price,$buy['price']);
			$price_sell=max($price,$sell['price']);
		    if($buy && $sell && floatval($price_buy)-floatval($price_sell)>=0){
				$amount=min($buy['num']-$buy['deal'],$sell['num']-$sell['deal']);
			    $rs[]=$mo->table('t_orders')->save(array('id'=>$buy['id'],'deal'=>array('exp','deal+'.$amount)));
				$rs[]=$mo->table('t_orders')->save(array('id'=>$sell['id'],'deal'=>array('exp','deal+'.$amount)));
				//$rs[]=$mo->table('t_trans')->add(array('buyid'=>$buy['id'],'sellid'=>$sell['id'],'ctime'=>time(),'num'=>$amount,'coin'=>$coin));

				$rs[]=$mo->table('t_trans')->add(array('buyid'=>$buy['id'],'sellid'=>$sell['id'],'ctime'=>time(),'price'=>$price_buy,'type'=>1,'uid'=>$buy['uid'],'num'=>$amount,'coin'=>$coin));
                $rs[]=$mo->table('t_trans')->add(array('buyid'=>$buy['id'],'sellid'=>$sell['id'],'ctime'=>time(),'price'=>$price_sell,'type'=>0,'uid'=>$sell['uid'],'num'=>$amount,'coin'=>$coin));

              //  $realnum = $amount - $amount*$this->sys['tradefee']/100;
                $realnum = $amount ;//- $amount*$this->sys['tradefee']/100;
				$rs[]=$mo->table('t_user')->save(array('id'=>$buy['uid'],'rmb_frozen'=>array('exp','rmb_frozen-'.($price_buy*$amount)),'xnb'=>array('exp','xnb+'.$realnum)));
                $total = $price_sell*$amount;
				$realtotal = $total - $total*$this->sys['tradefee']/100;
				$rs[]=$mo->table('t_user')->save(array('id'=>$sell['uid'],'xnb_frozen'=>array('exp','xnb_frozen-'.$amount),'rmb'=>array('exp','rmb+'.$realtotal)));
				$data['userid']=$_SESSION['USER_KEY_ID'];
				$data['money']=$total*$this->sys['tradefee']/100;
				$data['time']=time();
				$rs[]=$mo->table('t_sxf')->add($data);
				$rs[]=$mo->table('t_orders')->where('num=deal')->setField('status',1);

				if(chkArr($rs)){
					$mo->query('commit');
					$mo->query('unlock tables');
				}else{
					$mo->query('rollback');
				}
			}else{
			    break;
			}
			unset($rs);
		}
	}

	public function cancel(){
	    if(!chkNum($_POST['id'])||!chkStr($_POST['coin'])){$this->ajaxReturn('','请选择要撤销的委托！',1);exit;};
        
		$mo = new Model();
		$mo->query('set autocommit=0');
		$mo->query('lock tables t_user write,t_orders write');
		$rs = array();

		$Orders = $mo->table('t_orders')->where('id='.$_POST['id'].' and status=0')->find();
		if(!$Orders){$mo->query('rollback');$this->ajaxReturn('','无撤销项！',1);exit;}

		if($Orders['type']==0){
			if($_POST['coin']=='kg'){
				$rs[] = $mo->table('t_user')->save(array(
					'id'=>$Orders['uid'],
					'xnb'=>array('exp','xnb+'.($Orders['num']-$Orders['deal'])),
					'xnb_frozen'=>array('exp','xnb_frozen-'.($Orders['num']-$Orders['deal']))
				));
			}else{
				$rs[] = $mo->table('t_user')->save(array(
					'id'=>$Orders['uid'],
					'ks'=>array('exp','ks+'.($Orders['num']-$Orders['deal'])),
					'ks_frozen'=>array('exp','ks_frozen-'.($Orders['num']-$Orders['deal']))
				));
			}
		}else{
		    $rs[] = $mo->table('t_user')->save(array(
				'id'=>$Orders['uid'],
				'rmb'=>array('exp','rmb+'.(($Orders['num']-$Orders['deal'])*$Orders['price'])),
				'rmb_frozen'=>array('exp','rmb_frozen-'.(($Orders['num']-$Orders['deal'])*$Orders['price']))
            ));
		}

		$rs[] = $mo->table('t_orders')->where('id='.$_POST['id'])->delete();

		if(chkArr($rs)){
		    $mo->query('commit');
			$mo->query('unlock tables');
			$this->ajaxReturn('','撤销成功！',0);
		}else{
		    $mo->query('rollback');
			$this->ajaxReturn('','撤销失败！',1);
		}
	}
}